<template>
    <view class="page" :style="{'--color': color}" v-if="detail">
        <status-bar title='订单详情'></status-bar>
		<backTop v-if='toTop'></backTop>
		<view class="card p-20">
			<view class="d-flex a-center">
				<view class="flex-1">
					<view class="stateName" v-if="detail.state == 0">待支付</view>
					<view class="stateName" v-if="detail.state == 1">{{ detail.groupData && detail.groupData.state == 0 ? '待成团' : '待发货' }}</view>
					<view class="stateName" v-if="['2','3'].includes(detail.state)">{{ detail.delivery == 1 ? '待收货' : '待取货' }}</view>
					<view class="stateName" v-if="detail.state == 4">待评价</view>
					<view class="stateName" v-if="detail.state == 5">已评价</view>
					<view class="stateName" v-if="detail.state == 6">退款中</view>
					<view class="stateName" v-if="detail.state == 96">退款成功</view>
					<view class="stateName" v-if="detail.state == 97">已失效</view>
					<view class="stateName" v-if="detail.state == 98">已取消</view>
					<view class="stateInfo" v-if="detail.state == 0 && detail.endTime > 0">订单将在<count-down :time="detail.endTime" />关闭，请完成支付</view>
					<view class="stateInfo" v-if="detail.state == 1">宝贝正在打包中，请耐心等待</view>
					<view class="stateInfo" v-if="['2','3'].includes(detail.state)">宝贝正在运输中，请耐心等待</view>
					<view class="stateInfo" v-if="detail.state == 6">请耐心等待，如有疑问请联系商家！</view>
					<view class="stateInfo" v-if="['4','5','96','97','98'].includes(detail.state)">感谢您的光临，期待再次为您服务！</view>
				</view>
				<image class="stateImg" :src="staticUrl + '/images/unpay.png'" mode="widthFix" v-if="detail.state == 0"></image>
				<image class="stateImg" :src="staticUrl + '/images/unship.png'" mode="widthFix" v-if="detail.state == 1"></image>
				<image class="stateImg" :src="staticUrl + '/images/unreceipt.png'" mode="widthFix" v-if="['2','3'].includes(detail.state)"></image>
				<image class="stateImg" :src="staticUrl + '/images/complete.png'" mode="widthFix" v-if="['4','5','6','96'].includes(detail.state)"></image>
				<image class="stateImg" :src="staticUrl + '/images/cancel.png'" mode="widthFix" v-if="['97','98'].includes(detail.state)"></image>
			</view>
			<view class="bor_radius_20 m-top20" v-if="detail.delivery == 3 && (detail.state == 1 || detail.state == 2)">
				<map id="myMap" :longitude="longitude" :latitude="latitude" :markers="markers"></map>
			</view>
		</view>
		
		<!-- 团购 -->
		<view class="gbuy_user margin20" v-if="detail.state == 0 && detail.groupData">
			<view class="gbuy_user_timer">立即支付，即可开团</view>
			<view class="gbuy_user_list p-bot20" v-if="detail.userDatas && detail.userDatas.length">
				<view class="gbuy_user_item" v-for="(item,index) in detail.userDatas" :key="index">
					<image :src="$imgUrls(item.v_headimg)" mode="aspectFill" class="gbuy_user_avatar"></image>
					<view class="tag color6" v-if="item.v_id == detail.groupData.main_v_id">团长</view>
				</view>
				<view class="gbuy_user_item">
					<image :src="$imgUrls(detail.headImg)" mode="aspectFill" class="gbuy_user_avatar"></image>
					<view class="tag color5">待支付</view>
				</view>
			</view>
		</view>
		<view class="gbuy_user margin20" v-if="detail.state == 1 && detail.groupData && detail.groupData.state == 0">
			<view class="gbuy_user_timer" v-if="detail.groupData.missPeople > 0">还差<text class="size28 thmeColor bold">{{ detail.groupData.missPeople }}</text>人成团，剩余
				<count-down :time="detail.groupData.gameOver" fontSize="28" :txtColor="color" /></view>
			<view class="gbuy_user_list" v-if="detail.userDatas && detail.userDatas.length">
				<view class="gbuy_user_item" v-for="(item,index) in detail.userDatas" :key="index">
					<image :src="$imgUrls(item.v_headimg)" mode="aspectFill" class="gbuy_user_avatar"></image>
					<view class="tag color6" v-if="item.v_id == detail.groupData.main_v_id">团长</view>
				</view>
			</view>
			<button class="btn4 thmeBg t-letter10 m-top40" open-type="share">邀请好友</button>
		</view>
		<view class="gbuy_user margin20" v-if="detail.groupData && detail.groupData.state == 1">
			<view class="gbuy_user_scs flexac">
				<text class="iconfont icon-chenggong size48"></text>
				<text class="size36 m-left10">拼团成功</text>
			</view>
			<view class="gbuy_user_list p-bot20">
				<view class="gbuy_user_item" v-for="(item,index) in detail.userDatas" :key="index">
					<image :src="$imgUrls(item.v_headimg)" mode="aspectFill" class="gbuy_user_avatar"></image>
					<view class="tag color6" v-if="item.v_id == detail.groupData.main_v_id">团长</view>
				</view>
			</view>
		</view>
		
		<InstallStarte :pageData="pageData" :order_id="order_id" :detail="detail"></InstallStarte>
		
		<view class="card">
			<view class="store p-top10">
				<view class="size32 bold">{{ detail.shopName }}</view>
				<view class="d-flex a-center" v-if="detail.delivery == 2 || detail.delivery == 3">
					<view class="flex-1 color_66 m-right30">{{ detail.shopAdress || startUp.service_address }}</view>
					<view class="icon m-right30" :style="{background: hexToRgba(color, .05)}" @click="$common.Tel(detail.shopMobile || startUp.service_tel)">
						<text class="iconfont icon-dianhua size32 thmeColor bold"></text>
					</view>
					<view class="icon" :style="{background: hexToRgba(color, .05)}" @click="openMap">
						<text class="iconfont icon-wodeluxian size32 thmeColor bold"></text>
					</view>
				</view>
			</view>
			<view class="store m-bot10">
				<view class="d-flex m-top20" v-for="(item,index) in detail.goodsData" :key="index" @click="toGoods(item.goods_id)">
					<image class="img bor_radius_4" :src="item.goods_img ? $imgUrls(item.goods_img) : staticUrl + '/images/imageLoading.png'" mode="aspectFill"></image>
					<view class="flex-1 m-left20">
						<view class="ellipsis m-bot20">
							<text class="speTag" v-if="item.goodsType == 1">特价</text>
							<text class="speTag" v-if="item.goodsType == 2">团购</text>
							<text class="size28">{{ item.goods_name }}</text>
						</view>
						<view class="color_66 m-bot20">{{ item.specs_bind_text }}</view>
						<view>x {{ item.goods_num }}</view>
					</view>
					<view class="size32 thmeColor">￥{{ item.price }}</view>
				</view>
			</view>
			<view class="item">
				<view class="label">商品总价</view>
				<view class="price">￥{{ detail.total }}</view>
			</view>
			<view class="item">
				<view class="label">运费</view>
				<view class="price">￥{{ detail.express_fee }}</view>
			</view>
			<view class="item" v-if="detail.act_money > 0">
				<view class="label">{{ detail.usedActTitle }}<text class="sub">{{ detail.act_title }}</text></view>
				<view class="price">-￥{{ detail.act_money }}</view>
			</view>
			<view class="item" v-if="detail.vip_money > 0">
				<view class="label">{{ detail.vipActTitle }}<text class="sub">{{ detail.vip_title }}</text></view>
				<view class="price">-￥{{ detail.vip_money }}</view>
			</view>
			<view class="item" v-if="detail.dis_money > 0">
				<view class="label">优惠券<text class="sub">{{ detail.dis_title }}</text></view>
				<view class="price">-￥{{ detail.dis_money }}</view>
			</view>
			<view class="item" v-if="detail.fen_to_money > 0">
				<view class="label">积分抵扣<text class="sub">{{ detail.used_fen }}分</text></view>
				<view class="price">-￥{{ detail.fen_to_money }}</view>
			</view>
			<!-- all_payment：不算优惠 -->
			<view class="item">
				<view class="label">实付款{{ detail.payment > 0 ? '' : '(余额)' }}</view>
				<view class="price bold">￥{{ parseFloat(detail.payment) + parseFloat(detail.used_balance) }}</view>
			</view>
		</view>
        <view class="card">
            <view class="item">
                <view class="label">订单编号</view>
                <view>
                    <text class="value m-right10">{{ detail.order_code }}</text>
                    <text class="size28 thmeColor" @click="$pop.setClip(detail.order_code)">复制</text>
                </view>
            </view>
			<view class="item">
			    <view class="label">配送方式</view>
			    <view class="value">{{ deliveryName }}</view>
			</view>
			<view class="item" v-if="detail.add_time">
			    <view class="label">下单时间</view>
			    <view class="value">{{ $common.timeFormat(detail.add_time, 'Y-M-D h:m:s') }}</view>
			</view>
			<view class="item" v-if="detail.pay_time">
			    <view class="label">支付时间</view>
			    <view class="value">{{ $common.timeFormat(detail.pay_time, 'Y-M-D h:m:s') }}</view>
			</view>
			<view class="item" v-if="detail.delivery == 1 || detail.delivery == 3">
			    <view class="label">收货信息</view>
			    <view class="text-right">
					<view class="value m-bot4">{{ detail.address }}</view>
					<view class="value">{{ detail.uname }} {{ detail.utel }}</view>
				</view>
			</view>
			<view class="item" v-if="detail.remarks">
			    <view class="label">备注信息</view>
			    <view class="value">{{ detail.remarks }}</view>
			</view>
        </view>
		<view class="footer_info j-end">
			<view>
				<view class="btn plain" @click="toUrl('/orderPage/order/logistics?order_id=' + detail.order_id)" 
					v-if="detail.delivery == 1 && detail.courier_name">查看物流</view>
				<!-- pay_type:2 到付 -->
				<view class="btn plain" v-if="detail.state == 0 || (detail.pay_type == 2 && detail.state == 1)" @click="show_model(0)">取消订单</view>
				<view class="btn plain" v-if="detail.refuse_state == 1 && refundState.includes(detail.state)" @click="show_model(1)">退货退款</view>
				<view class="btn thmeBg white" v-if="detail.state == 0" @click="payNow">去支付</view>
				<view class="btn thmeBg white" v-if="detail.delivery == 1 && (detail.state == 2 || detail.state == 3)" @click="show_model(3)">确认收货</view>
				<view class="btn thmeBg white" v-if="detail.delivery == 2 && (detail.state == 2 || detail.state == 3)" @click="getCode">提货码</view>
				<view class="btn thmeBg white" @click="toUrl('/commentPage/comment/commentGoods?oid=' + order_id)" v-if="detail.state == 4">立即评价</view>
				<view class="btn thmeBg white" v-if="detail.state == 98" @click="buyAgain">再次购买</view>
			</view>
		</view>
		
		<!-- 提货码 -->
		<view class="mask flexac f-column" @click="codeInfo = ''" v-if="codeInfo">
			<view class="code_pop text-center" :style="{backgroundImage: 'url(' + staticUrl + '/images/pickup_code_pop_bg.png)'}" @click.stop>
				<view class="size32 p-top80 p-bot70">请向店员出示取货二维码</view>
				<image :src="$imgUrls(codeInfo.url)" mode="aspectFit" class="code_img"></image>
				<view class="size32 m-top40">{{ codeInfo.code }}</view>
			</view>
			<text class="iconfont icon-guanbi size60" @click="codeInfo = ''"></text>
		</view>
		
		<showModel v-if="showModal" type="99" :title="title" :msg="msg" :btn1="btn1" :btn2="btn2" @certain="certain" @cancelFunc="showModal = false"></showModel>
    </view>
</template>

<script>
    import { mapState } from 'vuex'
	import InstallStarte from '../components/InstallStarte/InstallStarte.vue'
    export default {
		components: {
			InstallStarte
		},
        data() {
            return {
				staticUrl: this.staticUrl,
				toTop: false,
                order_id: '',
                detail: '',
				codeInfo: '',
				showModal: false,
				modelType: '',
				title: '',
				msg: '',
				btn1: '',
				btn2: '',
				timer: null,
				pageData: '',
				longitude: 0,
				latitude: 0,
				markers: []
            }
        },
        computed: {
            ...mapState(['color', 'startUp', 'vid', 'logo']),
			deliveryName() {
				switch (this.detail.delivery){
					case '1':
						return this.detail.courier_name || '快递'
					case '2':
						return '自提'
					case '3':
						return this.detail.courier_name || '外卖'
				}
			},
			refundState() {
				if(this.detail.pay_type == 2) return ['2','3','5']
				return ['1','2','3','4','5']
			}
        },
        onLoad(e) {
            this.order_id = e.order_id
			
			// #ifdef MP
			uni.hideShareMenu()
			// #endif
        },
		onShow() {
			this.getDetail()
		},
        methods: {
            getDetail() {
                this.$http.post({
                    url: '/zzj_singleSaleApi/orderSingleDetails',
                    data: {
                        order_id: this.order_id
                    }
                }).then(res => {
                    if(res.errcode != 100) return
					let result = res.data || ''
					if(result.endTime > 0 && !this.timer) {
						this.timer = setInterval(() => {
							this.getDetail()
						}, 2000)
					}
					if(!result.endTime || result.endTime < 0) {
						if(result.state == 0) this.$back()
						this.clearTimer()
					}
					if(result.state > 0 && result.state < 6) this.getOrderDispatch()
					if(result.delivery == 3 && (result.state == 1 || result.state == 2)) this.addMarkers(result)
                    this.detail = result
                })
            },
			addMarkers(item) { // 添加标记点
				this.markers = [{
					id: 0,
					latitude: parseFloat(item.shopPointy),
					longitude: parseFloat(item.shopPointx),
					iconPath: this.$imgUrls(this.logo),
					width: 40,
					height: 40
				}, {
					id: 1,
					latitude: parseFloat(item.lat),
					longitude: parseFloat(item.lon),
					iconPath: this.$imgUrls(item.headImg),
					width: 40,
					height: 40
				}]
				this.longitude = this.markers[0].longitude
				this.latitude = this.markers[0].latitude
			},
			getOrderDispatch() {
				this.$http.post({
					url: '/dispatch/getOrderDispatch',
					data: {
						order_id: this.order_id
					}
				}).then(res => {
					if(res.code != 100) return
					this.pageData = res.data
				})
			},
			openMap() {
				uni.openLocation({
					longitude: parseFloat(this.detail.shopPointx),
					latitude: parseFloat(this.detail.shopPointy),
					name: this.detail.shopName,
					address: this.detail.shopAdress
				})
			},
			getCode() {
				this.$http.post({
					url: '/zzj_singleSaleApi/get_qrcode',
					data: {
						order_id: this.order_id
					}
				}).then(res => {
					if(res.url) this.codeInfo = res
				})
			},
			async show_model(type) {
				this.modelType = type
				if(type == 0) {
					this.title = '是否确定取消订单？'
					this.msg = '可在已取消列表找到'
					this.btn1 = '我再想想'
					this.btn2 = '确定'
					this.toUrl('/userPage/login/binding'); 
				}
				if(type == 1) {
					this.title = '是否确定退货退款？'
					this.msg = '退货退款成功后将不可撤回'
					this.btn1 = '我再想想'
					this.btn2 = '退意已决'
					this.toUrl('/userPage/login/binding'); 
				}
				if(type == 3) {
					this.title = '是否确定已收到宝贝？'
					this.msg = '确认收货后将不可撤销操作'
					this.btn1 = '取消'
					this.btn2 = '确认收货'
					if(this.detail.payment == 0) return this.toUrl('/userPage/login/binding'); 
					const Result = await this.$pop.getTxConfirm(this.detail.order_id)
					if(Result != 2) return this.toUrl('/userPage/login/binding'); 
					if(wx.openBusinessView) {
						wx.openBusinessView({
							businessType: 'weappOrderConfirm',
							extraData: {
								transaction_id: this.detail.transaction_id
							},
							success: e => {
								if(e.extraData.status == 'success') {
									this.receipt()
								}
							}
						})
					} else {
						this.$Toast('请先升级到最新的微信版本')
					}
				}
			},
			certain() {
				if(this.modelType == 0) { // 取消订单
					this.$http.post({
						url: '/zzj_singleSaleApi/cancelOrder',
						data: {
							order_id: this.order_id
						}
					}).then(res => {
						this.cancel(res)
					})
				}
				if(this.modelType == 1) { // 退货退款
					this.$http.post({
						url: '/zzj_singleSaleApi/refund',
						data: {
							order_id: this.order_id
						}
					}).then(res => {
						this.cancel(res)
					})
				}
				if(this.modelType == 3) { // 确认收货
					this.receipt()
				}
			},
			receipt() {
				this.$http.post({
					url: '/zzj_singleSaleApi/receivingGoods',
					data: {
						order_id: this.order_id
					}
				}).then(res => {
					this.cancel(res)
					if(res.status) this.toUrl('/orderPage/order/receiptSuccess?oid=' + this.order_id)
				})
			},
			cancel(res) {
				this.$Toast(res.msg)
				this.showModal = false
				this.getDetail()
			},
			payNow() {
				// #ifdef H5
				window.location.href = 'https://sra.mogoie.com/index.php/accountPay/weChatCashierPage?orderStr=' + this.detail.payID
				// #endif
				// #ifndef H5
				this.toUrl('/moneyPage/capital/checkstand?payid=' + this.detail.payID)
				// #endif	
			},
			buyAgain() {
				let goods = this.detail.goodsData || []
				if(goods.length == 1) {
					let param = '?goods_id=' + goods[0].goods_id + '&goods_num=' + goods[0].goods_num
					if(goods[0].specs_bind_id) param = param + '&specs_bind_id=' + goods[0].specs_bind_id + '&specs_bind_text=' + goods[0].specs_bind_text
					return this.toUrl('/orderPage/order/createOrders' + param)
				}
				let arr = []
				goods.forEach((item,index) => {
					this.$http.post({
						url: '/zzj_singleSaleApi/joinCart',
						data: {
							goods_id: item.goods_id,
							specs_bind_id: item.specs_bind_id,
							specs_bind_text: item.specs_bind_text,
							num: parseInt(item.goods_num)
						}
					}).then(res => {
						if(res.errcode != 100) return this.$Toast(res.msg)
						arr.push(res.car_id)
						if(index == goods.length - 1) {
							uni.setStorageSync('buyway', '')
							this.toUrl('/orderPage/order/createOrders?car_id=' + arr.join())
						}
					})
				})
			},
			hexToRgba(hex, opacity) {
				return 'rgba(' + parseInt('0x' + hex.slice(1, 3)) + ',' + parseInt('0x' + hex.slice(3, 5)) + ',' + parseInt('0x' + hex.slice(5, 7)) + ',' + opacity + ')'
			},
			clearTimer() {
				if(this.timer) {
					clearInterval(this.timer)
					this.timer = null
				}
			}
        },
		onShareAppMessage(res) {
			if(res.from == 'button') { // "邀请好友"参团按钮
				let { goods_name, goods_id, act_id, group_id, goods_img } = this.detail
				return {
					title: goods_name,
					path: '/pages/index/index?share_v_id=' + this.vid + '&pageType=3&gid=' + goods_id + '&aid=' + act_id + '&group_id=' + group_id,
					imageUrl: this.$imgUrls(goods_img)
				}
			}
		},
		onPageScroll(e) {
			if(e.scrollTop > 200) {
				this.toTop = true
			} else {
				this.toTop = false
			}
		},
		onHide() {
			this.clearTimer()
		},
		onUnload() {
			this.clearTimer()
		}
    }
</script>

<style lang="scss" scoped>
    .page {
        background-color: #f8f8f8;
		padding-bottom: calc(100rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(100rpx + env(safe-area-inset-bottom));
    }
    .card {
        width: 710rpx;
        background: #fff;
        border-radius: 10rpx;
        padding: 10rpx 20rpx;
        margin: 24rpx auto;
		&.p-20 {
			padding: 20rpx;
		}
		.stateName {
			font-size: 28rpx;
			color: #ff7e00;
			font-weight: bold;
			margin-bottom: 20rpx;
		}
		.stateInfo {
			font-size: 28rpx;
			color: #999;
		}
		.stateImg {
			width: 120rpx;
		}
		.store {
			border-bottom: 1rpx dashed #e4e4e4;
			padding-bottom: 20rpx;
			.icon {
				width: 60rpx;
				height: 60rpx;
				line-height: 60rpx;
				border-radius: 50%;
				text-align: center;
			}
		}
		.img {
			width: 160rpx;
			height: 160rpx;
		}
        .item {
            display: flex;
            justify-content: space-between;
            padding: 10rpx 0;
            .label {
                font-size: 28rpx;
                color: #666;
				flex-shrink: 0;
				min-width: 150rpx;
				max-width: 70%;
            }
			.sub {
				color: #999;
				margin-left: 10rpx;
			}
			.value {
				font-size: 28rpx;
				color: #333;
			}
			.price {
				font-size: 32rpx;
				color: var(--color);
			}
        }
    }
	#myMap {
		width: 100%;
		height: 500rpx;
	}
	.gbuy_user {
		width: 710rpx;
	}
	.footer_info {
		padding: 0 30rpx;
	}
	.btn {
		display: inline-block;
		width: 172rpx;
		height: 60rpx;
		line-height: 60rpx;
		border-radius: 30rpx;
		text-align: center;
		box-sizing: border-box;
		margin: 10rpx 0 0 20rpx;
		margin-bottom: calc(10rpx + constant(safe-area-inset-bottom));
		margin-bottom: calc(10rpx + env(safe-area-inset-bottom));
		font-size: 28rpx;
		&.plain {
			border: 2rpx solid #989898;
			color: #1b1b1b;
		}
	}
	.code_pop {
		width: 600rpx;
		height: 800rpx;
		background-size: 100% 100%;
		.code_img {
			width: 440rpx;
			height: 440rpx;
		}
	}
</style>